<template>
  <div class="order-confirm-page min-h-screen bg-gray-50 dark:bg-gray-900">
    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="lg:max-w-[1200px] mx-auto">
        <!-- 返回按钮 -->
        <div class="mb-6">
          <el-button
            link
            class="!px-0 !h-auto text-gray-600 hover:text-primary-600"
            @click="handleBack"
          >
            <el-icon class="mr-2"><ArrowLeft /></el-icon>
            返回
          </el-button>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="py-8">
          <el-skeleton :rows="10" animated />
        </div>

        <template v-else>
          <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            label-position="top"
            @submit.prevent="handleSubmit"
          >
            <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
              <!-- 左侧主要信息 -->
              <div class="lg:col-span-8 space-y-6">
                <!-- 收货地址/入住人/游客信息 -->
                <div
                  class="bg-white rounded-lg dark:bg-gray-800 dark:border dark:border-gray-700"
                >
                  <!-- 区域标题 -->
                  <div
                    class="flex items-center px-6 py-4 border-b border-gray-100 dark:border-gray-700"
                  >
                    <div
                      class="w-6 h-6 flex items-center justify-center rounded-full bg-primary-50 text-primary-600 mr-3"
                    >
                      <el-icon><Location /></el-icon>
                    </div>
                    <h2 class="text-lg font-medium dark:text-gray-100">
                      {{
                        orderType === "product"
                          ? "收货地址"
                          : orderType === "hotel"
                            ? "入住信息"
                            : orderType === "experience"
                              ? "体验信息"
                              : orderType === "guide"
                                ? "导游信息"
                                : "景点信息速览"
                      }}
                    </h2>
                  </div>

                  <div class="p-6">
                    <!-- 收货地址 - 仅文创商品显示 -->
                    <template v-if="orderType === 'product'">
                      <el-form-item
                        prop="addressId"
                        :rules="{ required: true, message: '请选择收货地址' }"
                      >
                        <div
                          v-if="selectedAddress"
                          class="group relative border border-gray-200 dark:border-gray-700 rounded-lg p-5 hover:border-primary-500 cursor-pointer transition-all duration-200"
                          @click="showAddressDialog = true"
                        >
                          <div class="flex items-center justify-between mb-3">
                            <div class="flex items-center">
                              <span class="font-medium text-lg">{{
                                selectedAddress.name
                              }}</span>
                              <span class="text-gray-500 mx-4">{{
                                selectedAddress.phone
                              }}</span>
                              <el-tag
                                v-if="selectedAddress.isDefault"
                                size="small"
                                type="primary"
                              >
                                默认
                              </el-tag>
                            </div>
                            <el-button
                              type="primary"
                              link
                              class="opacity-0 group-hover:opacity-100 transition-opacity duration-200"
                            >
                              更换地址
                              <el-icon class="ml-1"><ArrowRight /></el-icon>
                            </el-button>
                          </div>
                          <div class="text-gray-600 text-sm leading-relaxed">
                            {{ selectedAddress.fullAddress }}
                          </div>
                        </div>
                        <div
                          v-else
                          class="border border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer hover:border-primary-500 transition-colors duration-200"
                          @click="showAddressDialog = true"
                        >
                          <el-icon class="text-4xl text-gray-400 mb-3"
                            ><Plus
                          /></el-icon>
                          <div class="text-gray-500">添加收货地址</div>
                        </div>
                      </el-form-item>
                    </template>

                    <!-- 入住信息 - 仅酒店预订显示 -->
                    <template v-if="orderType === 'hotel'">
                      <!-- 入住日期选择 -->
                      <div class="mb-6">
                        <div class="grid grid-cols-2 gap-4">
                          <div class="space-y-2">
                            <label
                              class="text-sm text-gray-600 dark:text-gray-400"
                              >入住日期</label
                            >
                            <el-date-picker
                              v-model="formData.checkIn"
                              type="date"
                              placeholder="选择入住日期"
                              :disabled-date="disabledDate"
                              class="!w-full dark:bg-gray-800"
                            />
                          </div>
                          <div class="space-y-2">
                            <label
                              class="text-sm text-gray-600 dark:text-gray-400"
                              >离店日期</label
                            >
                            <el-date-picker
                              v-model="formData.checkOut"
                              type="date"
                              placeholder="选择离店日期"
                              :disabled-date="disabledCheckoutDate"
                              class="!w-full dark:bg-gray-800"
                            />
                          </div>
                        </div>
                        <div
                          class="mt-2 text-sm text-gray-500 dark:text-gray-400"
                        >
                          共
                          <span
                            class="text-primary-600 dark:text-primary-400 font-medium"
                            >{{ calculateNights() }}</span
                          >
                          晚
                        </div>
                      </div>

                      <!-- 入住人列表 -->
                      <div class="space-y-4">
                        <div class="flex items-center justify-between">
                          <h3 class="font-medium dark:text-gray-100">
                            入住人信息
                          </h3>
                          <el-button
                            v-if="formData.guests.length < maxGuests"
                            type="primary"
                            link
                            @click="addGuest"
                          >
                            <el-icon class="mr-1"><Plus /></el-icon>
                            添加入住人
                          </el-button>
                        </div>

                        <div
                          v-for="(guest, index) in formData.guests"
                          :key="index"
                          class="bg-gray-50 dark:bg-gray-700 rounded-lg p-5 transition-all duration-200"
                        >
                          <div class="flex items-center justify-between mb-4">
                            <h4
                              class="font-medium flex items-center dark:text-gray-100"
                            >
                              <span
                                class="w-6 h-6 flex items-center justify-center rounded-full bg-primary-50 text-primary-600 mr-2 text-sm"
                              >
                                {{ index + 1 }}
                              </span>
                              入住人信息
                            </h4>
                            <el-button
                              v-if="index > 0"
                              type="danger"
                              link
                              @click="removeGuest(index)"
                            >
                              删除
                            </el-button>
                          </div>
                          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <el-form-item
                              :prop="'guests.' + index + '.name'"
                              :rules="[
                                { required: true, message: '请输入入住人姓名' },
                                {
                                  min: 2,
                                  max: 20,
                                  message: '长度在 2 到 20 个字符',
                                },
                              ]"
                            >
                              <el-input
                                v-model="guest.name"
                                placeholder="请输入姓名"
                                class="dark:bg-gray-800 dark:text-gray-300"
                              />
                            </el-form-item>
                            <el-form-item :prop="'guests.' + index + '.idType'">
                              <el-select
                                v-model="guest.idType"
                                placeholder="证件类型"
                                class="!w-full dark:bg-gray-800"
                              >
                                <el-option label="身份证" value="idcard" />
                                <el-option label="护照" value="passport" />
                              </el-select>
                            </el-form-item>
                            <el-form-item
                              :prop="'guests.' + index + '.idNumber'"
                              :rules="[
                                { required: true, message: '请输入证件号码' },
                                { validator: validateIdNumber },
                              ]"
                            >
                              <el-input
                                v-model="guest.idNumber"
                                placeholder="请输入证件号码"
                                class="dark:bg-gray-800 dark:text-gray-300"
                              />
                            </el-form-item>
                          </div>
                        </div>
                      </div>
                    </template>

                    <!-- 特色体验信息 -->
                    <template v-if="orderType === 'experience'">
                      <div class="space-y-6">
                        <!-- 体验基本信息 -->
                        <div class="space-y-4">
                          <h3 class="text-base font-medium dark:text-gray-100">
                            体验信息
                          </h3>
                          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div class="space-y-2">
                              <label
                                class="text-sm text-gray-600 dark:text-gray-400"
                                >体验日期</label
                              >
                              <el-date-picker
                                v-model="formData.experienceDate"
                                type="date"
                                placeholder="请选择体验日期"
                                :disabled-date="disabledDate"
                                class="!w-full"
                              />
                            </div>
                            <div class="space-y-2">
                              <label
                                class="text-sm text-gray-600 dark:text-gray-400"
                                >参与人数</label
                              >
                              <div class="text-gray-900 dark:text-gray-100">
                                {{ formData.participants?.length || 1 }}人
                              </div>
                            </div>
                          </div>
                        </div>

                        <!-- 体验者信息 -->
                        <div class="space-y-4">
                          <div class="flex items-center justify-between">
                            <h3
                              class="text-base font-medium dark:text-gray-100"
                            >
                              体验者信息
                            </h3>
                            <el-button
                              v-if="
                                formData.participants.length < maxParticipants
                              "
                              type="primary"
                              link
                              @click="addParticipant"
                            >
                              <el-icon class="mr-1"><Plus /></el-icon>
                              添加体验者
                            </el-button>
                          </div>

                          <div
                            v-for="(
                              participant, index
                            ) in formData.participants"
                            :key="index"
                            class="bg-gray-50 dark:bg-gray-700 rounded-lg p-5"
                          >
                            <div class="flex items-center justify-between mb-4">
                              <h4
                                class="font-medium flex items-center dark:text-gray-100"
                              >
                                <span
                                  class="w-6 h-6 flex items-center justify-center rounded-full bg-primary-50 text-primary-600 mr-2 text-sm"
                                >
                                  {{ index + 1 }}
                                </span>
                                体验者信息
                              </h4>
                              <el-button
                                v-if="index > 0"
                                type="danger"
                                link
                                @click="removeParticipant(index)"
                              >
                                删除
                              </el-button>
                            </div>
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                              <el-form-item
                                :prop="'participants.' + index + '.name'"
                                :rules="[
                                  {
                                    required: true,
                                    message: '请输入体验者姓名',
                                  },
                                  {
                                    min: 2,
                                    max: 20,
                                    message: '长度在 2 到 20 个字符',
                                  },
                                ]"
                              >
                                <el-input
                                  v-model="participant.name"
                                  placeholder="请输入姓名"
                                  class="dark:bg-gray-800 dark:text-gray-300"
                                />
                              </el-form-item>
                              <el-form-item
                                :prop="'participants.' + index + '.phone'"
                                :rules="[
                                  { required: true, message: '请输入手机号码' },
                                  {
                                    pattern: /^1[3-9]\d{9}$/,
                                    message: '请输入正确的手机号码',
                                  },
                                ]"
                              >
                                <el-input
                                  v-model="participant.phone"
                                  placeholder="请输入手机号码"
                                  class="dark:bg-gray-800 dark:text-gray-300"
                                />
                              </el-form-item>
                              <el-form-item
                                :prop="'participants.' + index + '.idNumber'"
                                :rules="[
                                  {
                                    required: true,
                                    message: '请输入身份证号码',
                                  },
                                  {
                                    pattern:
                                      /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                                    message: '请输入正确的身份证号码',
                                  },
                                ]"
                              >
                                <el-input
                                  v-model="participant.idNumber"
                                  placeholder="请输入身份证号码"
                                  class="dark:bg-gray-800 dark:text-gray-300"
                                />
                              </el-form-item>
                            </div>
                          </div>
                        </div>

                        <!-- 体验须知 -->
                        <div
                          class="bg-gray-50 dark:bg-gray-700 rounded-lg p-4 space-y-2 text-sm"
                        >
                          <h4 class="font-medium dark:text-gray-100">
                            体验须知
                          </h4>
                          <ul
                            class="list-disc list-inside space-y-1 text-gray-600 dark:text-gray-400"
                          >
                            <li>
                              请确保填写的体验者信息准确，参与体验时需出示相关证件
                            </li>
                            <li>
                              订单确认后将发送确认短信和邮件到您的手机和邮箱
                            </li>
                            <li>如需发票，请在体验完成后向工作人员索取</li>
                            <li>体验开始前24小时内取消将收取全额费用</li>
                          </ul>
                        </div>
                      </div>
                    </template>

                    <!-- 景点信息速览 - 仅门票显示 -->
                    <template v-if="orderType === 'ticket'">
                      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="space-y-4">
                          <div class="flex items-start space-x-3">
                            <el-icon
                              class="text-primary-600 dark:text-primary-400 mt-1"
                              ><Clock
                            /></el-icon>
                            <div>
                              <div
                                class="text-sm text-gray-500 dark:text-gray-400"
                              >
                                开放时间
                              </div>
                              <div class="text-gray-900 dark:text-white">
                                09:00-17:30
                              </div>
                            </div>
                          </div>
                          <div class="flex items-start space-x-3">
                            <el-icon
                              class="text-primary-600 dark:text-primary-400 mt-1"
                              ><Timer
                            /></el-icon>
                            <div>
                              <div
                                class="text-sm text-gray-500 dark:text-gray-400"
                              >
                                建议游玩
                              </div>
                              <div class="text-gray-900 dark:text-white">
                                2-3小时
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="space-y-4">
                          <div class="flex items-start space-x-3">
                            <el-icon
                              class="text-primary-600 dark:text-primary-400 mt-1"
                              ><Location
                            /></el-icon>
                            <div>
                              <div
                                class="text-sm text-gray-500 dark:text-gray-400"
                              >
                                景点地址
                              </div>
                              <div class="text-gray-900 dark:text-white">
                                {{
                                  formData.spotAddress ||
                                  "广西贵港市港北区江滨路1号"
                                }}
                              </div>
                            </div>
                          </div>
                          <div class="flex items-start space-x-3">
                            <el-icon
                              class="text-primary-600 dark:text-primary-400 mt-1"
                              ><InfoFilled
                            /></el-icon>
                            <div>
                              <div
                                class="text-sm text-gray-500 dark:text-gray-400"
                              >
                                温馨提示
                              </div>
                              <div class="text-gray-900 dark:text-white">
                                {{ spotInfo.tips }}
                              </div>
                            </div>
                          </div>
                        </div>

                        <!-- 景点天气信息 -->
                        <div
                          class="md:col-span-2 bg-gray-50 dark:bg-gray-700 rounded-lg p-4"
                        >
                          <div class="flex items-center justify-between">
                            <div class="flex items-center space-x-3">
                              <el-icon
                                class="text-primary-600 dark:text-primary-400"
                                ><Sunny
                              /></el-icon>
                              <div>
                                <div
                                  class="text-sm text-gray-500 dark:text-gray-400"
                                >
                                  今日天气
                                </div>
                                <div class="text-gray-900 dark:text-white">
                                  {{ weatherInfo.temperature }}
                                </div>
                              </div>
                            </div>
                            <div class="text-sm text-gray-500">
                              <span class="text-primary-600">适宜游玩</span>
                              <el-tooltip
                                content="天气晴朗，适合游玩，请做好防晒"
                              >
                                <el-icon class="ml-1"
                                  ><QuestionFilled
                                /></el-icon>
                              </el-tooltip>
                            </div>
                          </div>
                        </div>
                      </div>
                    </template>

                    <!-- 导游基本信息 -->
                    <template v-if="orderType === 'guide'">
                      <!-- 导游基本信息展示 -->
                      <div class="space-y-4">
                        <div
                          v-for="(item, index) in orderItems"
                          :key="index"
                          class="flex gap-4 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
                        >
                          <el-image
                            :src="item.image"
                            fit="cover"
                            class="w-20 h-20 rounded-lg flex-shrink-0 border border-gray-100 dark:border-gray-600"
                          >
                            <template #error>
                              <div
                                class="h-full w-full flex items-center justify-center bg-gray-100 dark:bg-gray-700"
                              >
                                <el-icon class="text-gray-400"
                                  ><Picture
                                /></el-icon>
                              </div>
                            </template>
                          </el-image>
                          <div class="flex-1">
                            <div
                              class="text-lg font-medium mb-2 dark:text-gray-100"
                            >
                              {{ item.title }}
                            </div>
                            <div
                              class="text-gray-500 dark:text-gray-400 text-sm mb-4"
                            >
                              {{ item.specs }}
                            </div>
                            <div class="flex justify-between items-end">
                              <div
                                class="text-primary-500 dark:text-primary-400 font-medium"
                              >
                                ¥{{ item.price }}/天
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- 导游须知 -->
                      <div
                        class="bg-gray-50 dark:bg-gray-700 rounded-lg p-4 space-y-2 text-sm mt-6"
                      >
                        <h4 class="font-medium dark:text-gray-100">导游须知</h4>
                        <ul
                          class="list-disc list-inside space-y-1 text-gray-600 dark:text-gray-400"
                        >
                          <li>
                            请确保填写的联系人信息准确，导游将通过此联系方式与您联系
                          </li>
                          <li>
                            订单确认后将发送确认短信和邮件到您的手机和邮箱
                          </li>
                          <li>如需发票，请在行程结束后向导游索取</li>
                          <li>行程开始前24小时内取消将收取全额费用</li>
                        </ul>
                      </div>
                    </template>
                  </div>
                </div>

                <!-- 商品信息 -->
                <div
                  class="bg-white rounded-lg dark:bg-gray-800 dark:border dark:border-gray-700"
                >
                  <div
                    class="flex items-center px-6 py-4 border-b border-gray-100 dark:border-gray-700"
                  >
                    <div
                      class="w-6 h-6 flex items-center justify-center rounded-full bg-primary-50 text-primary-600 mr-3"
                    >
                      <el-icon><ShoppingBag /></el-icon>
                    </div>
                    <h2 class="text-lg font-medium dark:text-gray-100">
                      {{
                        orderType === "guide" ? "预约信息" : getOrderItemTitle
                      }}
                    </h2>
                  </div>

                  <div class="p-6 space-y-6">
                    <!-- 商品订单信息 -->
                    <template v-if="orderType === 'product'">
                      <div class="space-y-4">
                        <div
                          v-for="(item, index) in orderItems"
                          :key="index"
                          class="flex gap-4 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
                        >
                          <el-image
                            :src="item.image"
                            class="w-24 h-24 object-cover rounded-lg"
                          />
                          <div class="flex-1">
                            <div class="flex justify-between">
                              <div>
                                <h3
                                  class="text-base font-medium mb-2 dark:text-gray-100"
                                >
                                  {{ item.title }}
                                </h3>
                                <p
                                  class="text-sm text-gray-500 dark:text-gray-400"
                                >
                                  {{ item.specs }}
                                </p>
                              </div>
                              <div class="text-right">
                                <div
                                  class="text-lg font-medium text-primary-600 dark:text-primary-400"
                                >
                                  ¥{{ item.price }}
                                </div>
                                <div
                                  class="text-sm text-gray-500 dark:text-gray-400"
                                >
                                  x{{ item.quantity }}
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </template>

                    <!-- 门票订单信息 -->
                    <template v-if="orderType === 'ticket'">
                      <div class="space-y-4">
                        <h3 class="text-base font-medium dark:text-gray-100">
                          景点信息
                        </h3>
                        <div class="grid grid-cols-1 gap-4">
                          <div class="space-y-2">
                            <div
                              class="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
                            >
                              <div class="flex gap-4">
                                <el-image
                                  :src="orderItems[0]?.image"
                                  class="w-24 h-24 object-cover rounded-lg"
                                />
                                <div class="space-y-2">
                                  <h4
                                    class="text-base font-medium dark:text-gray-100"
                                  >
                                    {{ orderItems[0]?.title.split(" - ")[0] }}
                                  </h4>
                                  <div
                                    class="text-sm text-gray-500 dark:text-gray-400"
                                  >
                                    {{ orderItems[0]?.specs }}
                                  </div>
                                  <div
                                    class="text-sm text-gray-500 dark:text-gray-400"
                                  >
                                    门票类型：{{
                                      orderItems[0]?.title.split(" - ")[1]
                                    }}
                                  </div>
                                </div>
                              </div>
                              <div class="text-right">
                                <div
                                  class="text-lg font-medium text-primary-600 dark:text-primary-400"
                                >
                                  ¥{{ orderItems[0]?.price }}
                                </div>
                                <div
                                  class="text-sm text-gray-500 dark:text-gray-400"
                                >
                                  x{{ formData.visitors?.length || 1 }}
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- 游玩日期 -->
                      <div class="space-y-4">
                        <h3 class="text-base font-medium dark:text-gray-100">
                          游玩日期
                        </h3>
                        <el-form-item
                          prop="visitDate"
                          :rules="[
                            { required: true, message: '请选择游玩日期' },
                          ]"
                        >
                          <el-date-picker
                            v-model="formData.visitDate"
                            type="date"
                            placeholder="请选择游玩日期"
                            :disabled-date="disabledDate"
                            class="!w-full"
                          />
                        </el-form-item>
                      </div>

                      <!-- 游客信息 -->
                      <div class="space-y-4">
                        <div class="flex items-center justify-between">
                          <h3 class="text-base font-medium dark:text-gray-100">
                            游客信息
                          </h3>
                          <el-button
                            v-if="formData.visitors.length < maxVisitors"
                            type="primary"
                            link
                            @click="addVisitor"
                          >
                            <el-icon class="mr-1"><Plus /></el-icon>
                            添加游客
                          </el-button>
                        </div>

                        <div
                          v-for="(visitor, index) in formData.visitors"
                          :key="index"
                          class="bg-gray-50 dark:bg-gray-700 rounded-lg p-5"
                        >
                          <div class="flex items-center justify-between mb-4">
                            <h4
                              class="font-medium flex items-center dark:text-gray-100"
                            >
                              <span
                                class="w-6 h-6 flex items-center justify-center rounded-full bg-primary-50 text-primary-600 mr-2 text-sm"
                              >
                                {{ index + 1 }}
                              </span>
                              游客信息
                            </h4>
                            <el-button
                              v-if="index > 0"
                              type="danger"
                              link
                              @click="removeVisitor(index)"
                            >
                              删除
                            </el-button>
                          </div>
                          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <el-form-item
                              :prop="'visitors.' + index + '.name'"
                              :rules="[
                                { required: true, message: '请输入游客姓名' },
                                {
                                  min: 2,
                                  max: 20,
                                  message: '长度在 2 到 20 个字符',
                                },
                              ]"
                            >
                              <el-input
                                v-model="visitor.name"
                                placeholder="请输入姓名"
                              />
                            </el-form-item>
                            <el-form-item
                              :prop="'visitors.' + index + '.phone'"
                              :rules="[
                                { required: true, message: '请输入手机号码' },
                                {
                                  pattern: /^1[3-9]\d{9}$/,
                                  message: '请输入正确的手机号码',
                                },
                              ]"
                            >
                              <el-input
                                v-model="visitor.phone"
                                placeholder="请输入手机号码"
                              />
                            </el-form-item>
                            <el-form-item
                              :prop="'visitors.' + index + '.idNumber'"
                              :rules="[
                                { required: true, message: '请输入身份证号码' },
                                {
                                  pattern:
                                    /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                                  message: '请输入正确的身份证号码',
                                },
                              ]"
                            >
                              <el-input
                                v-model="visitor.idNumber"
                                placeholder="请输入身份证号码"
                              />
                            </el-form-item>
                          </div>
                        </div>
                      </div>
                    </template>

                    <!-- 酒店订单信息 -->
                    <template v-if="orderType === 'hotel'">
                      <div class="space-y-4">
                        <h3 class="text-base font-medium dark:text-gray-100">
                          入住信息
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div class="space-y-2">
                            <label
                              class="text-sm text-gray-600 dark:text-gray-400"
                              >入住日期</label
                            >
                            <div
                              class="flex items-center text-gray-900 dark:text-gray-100"
                            >
                              <span>{{ formatDate(formData.checkIn) }}</span>
                              <el-icon class="mx-2"><ArrowRight /></el-icon>
                              <span>{{ formatDate(formData.checkOut) }}</span>
                              <span class="ml-2 text-sm text-gray-500"
                                >(共{{ calculateNights() }}晚)</span
                              >
                            </div>
                          </div>
                          <div class="space-y-2">
                            <label
                              class="text-sm text-gray-600 dark:text-gray-400"
                              >房间数量</label
                            >
                            <div class="text-gray-900 dark:text-gray-100">
                              1间
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- 入住人信息 -->
                      <div class="space-y-4">
                        <h3 class="text-base font-medium dark:text-gray-100">
                          入住人信息
                        </h3>
                        <div
                          v-for="(guest, index) in formData.guests"
                          :key="index"
                          class="bg-gray-50 dark:bg-gray-700 rounded-lg p-5"
                        >
                          <div class="flex items-center mb-4">
                            <span
                              class="w-6 h-6 flex items-center justify-center rounded-full bg-primary-50 text-primary-600 mr-2 text-sm"
                            >
                              {{ index + 1 }}
                            </span>
                            <span class="font-medium dark:text-gray-100"
                              >入住人信息</span
                            >
                          </div>
                          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div class="space-y-1">
                              <label
                                class="text-sm text-gray-500 dark:text-gray-400"
                                >姓名</label
                              >
                              <div class="text-gray-900 dark:text-gray-100">
                                {{ guest.name || "-" }}
                              </div>
                            </div>
                            <div class="space-y-1">
                              <label
                                class="text-sm text-gray-500 dark:text-gray-400"
                                >证件类型</label
                              >
                              <div class="text-gray-900 dark:text-gray-100">
                                {{
                                  guest.idType === "idcard" ? "身份证" : "护照"
                                }}
                              </div>
                            </div>
                            <div class="space-y-1">
                              <label
                                class="text-sm text-gray-500 dark:text-gray-400"
                                >证件号码</label
                              >
                              <div class="text-gray-900 dark:text-gray-100">
                                {{ guest.idNumber || "-" }}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- 预订信息 -->
                      <div class="space-y-4">
                        <h3 class="text-base font-medium dark:text-gray-100">
                          预订信息
                        </h3>
                        <div class="grid grid-cols-1 gap-4">
                          <div class="space-y-2">
                            <div
                              class="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
                            >
                              <div class="space-y-1">
                                <label
                                  class="text-sm text-gray-600 dark:text-gray-400"
                                  >酒店名称</label
                                >
                                <div
                                  class="text-gray-900 dark:text-gray-100 font-medium"
                                >
                                  {{ orderItems[0]?.title.split(" - ")[0] }}
                                </div>
                              </div>
                              <div class="space-y-1 text-right">
                                <label
                                  class="text-sm text-gray-600 dark:text-gray-400"
                                  >房型</label
                                >
                                <div class="text-gray-900 dark:text-gray-100">
                                  {{ orderItems[0]?.title.split(" - ")[1] }}
                                </div>
                              </div>
                            </div>
                          </div>
                          <div class="grid grid-cols-2 gap-4">
                            <div class="space-y-2">
                              <label
                                class="text-sm text-gray-600 dark:text-gray-400"
                                >预计到店时间</label
                              >
                              <div class="text-gray-900 dark:text-gray-100">
                                14:00后
                              </div>
                              <p class="text-xs text-gray-500">
                                酒店办理入住时间为14:00后，如需提前到店请联系酒店
                              </p>
                            </div>
                            <div class="space-y-2">
                              <label
                                class="text-sm text-gray-600 dark:text-gray-400"
                                >特殊要求</label
                              >
                              <div class="text-gray-900 dark:text-gray-100">
                                {{ formData.remark || "无" }}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- 预订须知 -->
                      <div
                        class="bg-gray-50 dark:bg-gray-700 rounded-lg p-4 space-y-2 text-sm"
                      >
                        <h4 class="font-medium dark:text-gray-100">预订须知</h4>
                        <ul
                          class="list-disc list-inside space-y-1 text-gray-600 dark:text-gray-400"
                        >
                          <li>
                            请确保填写的入住人信息准确，入住时需出示相关证件
                          </li>
                          <li>
                            订单确认后将发送确认短信和邮件到您的手机和邮箱
                          </li>
                          <li>如需发票，请在入住时向酒店前台索取</li>
                          <li>入住前24小时内取消预订将收取首晚房费</li>
                        </ul>
                      </div>
                    </template>

                    <!-- 特色体验订单信息 -->
                    <template v-if="orderType === 'experience'">
                      <div class="space-y-4">
                        <h3 class="text-base font-medium dark:text-gray-100">
                          体验信息
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div class="space-y-2">
                            <label
                              class="text-sm text-gray-600 dark:text-gray-400"
                              >体验日期</label
                            >
                            <div class="text-gray-900 dark:text-gray-100">
                              {{ formatDate(formData.experienceDate) }}
                            </div>
                          </div>
                          <div class="space-y-2">
                            <label
                              class="text-sm text-gray-600 dark:text-gray-400"
                              >参与人数</label
                            >
                            <div class="text-gray-900 dark:text-gray-100">
                              {{ formData.participants?.length || 1 }}人
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- 体验者信息 -->
                      <div class="space-y-4">
                        <h3 class="text-base font-medium dark:text-gray-100">
                          体验者信息
                        </h3>
                        <div
                          v-for="(participant, index) in formData.participants"
                          :key="index"
                          class="bg-gray-50 dark:bg-gray-700 rounded-lg p-5"
                        >
                          <div class="flex items-center mb-4">
                            <span
                              class="w-6 h-6 flex items-center justify-center rounded-full bg-primary-50 text-primary-600 mr-2 text-sm"
                            >
                              {{ index + 1 }}
                            </span>
                            <span class="font-medium dark:text-gray-100"
                              >体验者信息</span
                            >
                          </div>
                          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div class="space-y-1">
                              <label
                                class="text-sm text-gray-500 dark:text-gray-400"
                                >姓名</label
                              >
                              <div class="text-gray-900 dark:text-gray-100">
                                {{ participant.name || "-" }}
                              </div>
                            </div>
                            <div class="space-y-1">
                              <label
                                class="text-sm text-gray-500 dark:text-gray-400"
                                >手机号码</label
                              >
                              <div class="text-gray-900 dark:text-gray-100">
                                {{ participant.phone || "-" }}
                              </div>
                            </div>
                            <div class="space-y-1">
                              <label
                                class="text-sm text-gray-500 dark:text-gray-400"
                                >身份证号码</label
                              >
                              <div class="text-gray-900 dark:text-gray-100">
                                {{ participant.idNumber || "-" }}
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- 体验须知 -->
                      <div
                        class="bg-gray-50 dark:bg-gray-700 rounded-lg p-4 space-y-2 text-sm"
                      >
                        <h4 class="font-medium dark:text-gray-100">体验须知</h4>
                        <ul
                          class="list-disc list-inside space-y-1 text-gray-600 dark:text-gray-400"
                        >
                          <li>
                            请确保填写的体验者信息准确，参与体验时需出示相关证件
                          </li>
                          <li>
                            订单确认后将发送确认短信和邮件到您的手机和邮箱
                          </li>
                          <li>如需发票，请在体验完成后向工作人员索取</li>
                          <li>体验开始前24小时内取消将收取全额费用</li>
                        </ul>
                      </div>
                    </template>

                    <!-- 导游预约信息 -->
                    <template v-if="orderType === 'guide'">
                      <!-- 预约日期和时间 -->
                      <div class="grid grid-cols-2 gap-6 mb-6">
                        <div class="space-y-2">
                          <label
                            class="text-sm text-gray-600 dark:text-gray-400"
                            >预约日期</label
                          >
                          <div
                            class="text-gray-900 dark:text-gray-100 font-medium p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"
                          >
                            {{
                              formData.guideDate
                                ? dayjs(formData.guideDate).format("YYYY-MM-DD")
                                : ""
                            }}
                          </div>
                        </div>
                        <div class="space-y-2">
                          <label
                            class="text-sm text-gray-600 dark:text-gray-400"
                            >开始时间</label
                          >
                          <div
                            class="text-gray-900 dark:text-gray-100 font-medium p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"
                          >
                            {{ formData.guideTime }}
                          </div>
                        </div>
                      </div>

                      <!-- 预约路线信息 -->
                      <div class="mb-6" v-if="formData.routeName">
                        <div class="space-y-2">
                          <label
                            class="text-sm text-gray-600 dark:text-gray-400"
                            >预约路线</label
                          >
                          <div
                            class="text-gray-900 dark:text-gray-100 font-medium p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"
                          >
                            {{ formData.routeName }}
                          </div>
                        </div>
                      </div>

                      <!-- 联系人信息表单 -->
                      <div class="form-section mb-6">
                        <h3
                          class="text-base font-medium mb-4 dark:text-gray-100"
                        >
                          联系人信息
                        </h3>
                        <el-form-item
                          prop="contactPerson.name"
                          :rules="{
                            required: true,
                            message: '请填写联系人姓名',
                          }"
                        >
                          <el-input
                            v-model="formData.contactPerson.name"
                            placeholder="联系人姓名"
                          />
                        </el-form-item>
                        <el-form-item
                          prop="contactPerson.phone"
                          :rules="{
                            required: true,
                            message: '请填写联系人电话',
                          }"
                        >
                          <el-input
                            v-model="formData.contactPerson.phone"
                            placeholder="联系人电话"
                          />
                        </el-form-item>
                        <el-form-item
                          prop="contactPerson.idNumber"
                          :rules="{
                            required: true,
                            message: '请填写联系人身份证号',
                          }"
                        >
                          <el-input
                            v-model="formData.contactPerson.idNumber"
                            placeholder="联系人身份证号"
                          />
                        </el-form-item>
                      </div>

                      <!-- 参与人数 -->
                      <div class="form-section mb-6">
                        <h3
                          class="text-base font-medium mb-4 dark:text-gray-100"
                        >
                          参与信息
                        </h3>
                        <div class="flex items-center justify-between mb-4">
                          <div class="font-medium dark:text-gray-200">
                            参与人数
                          </div>
                          <el-input-number
                            v-model="formData.people"
                            :min="1"
                            :max="20"
                            size="small"
                          />
                        </div>
                      </div>

                      <!-- 备注 -->
                      <div class="form-section">
                        <h3
                          class="text-base font-medium mb-4 dark:text-gray-100"
                        >
                          备注信息
                        </h3>
                        <el-form-item prop="remark">
                          <el-input
                            v-model="formData.remark"
                            type="textarea"
                            :rows="3"
                            placeholder="如有特殊需求，请在此备注"
                            maxlength="200"
                            show-word-limit
                          />
                        </el-form-item>
                      </div>
                    </template>
                  </div>
                </div>
              </div>

              <!-- 右侧订单信息 -->
              <div class="lg:col-span-4">
                <div
                  class="bg-white dark:bg-gray-800 rounded-lg p-6 lg:sticky lg:top-24 dark:border dark:border-gray-700"
                >
                  <h2 class="text-lg font-medium mb-6 dark:text-gray-100">
                    费用明细
                  </h2>

                  <!-- 费用明细 -->
                  <div class="space-y-4">
                    <!-- 商品订单费用明细 -->
                    <template v-if="orderType === 'product'">
                      <div
                        class="flex justify-between text-gray-500 dark:text-gray-400"
                      >
                        <span>商品总额</span>
                        <span>¥{{ calculateProductTotal() }}</span>
                      </div>
                      <div
                        class="flex justify-between text-gray-500 dark:text-gray-400"
                      >
                        <span>运费</span>
                        <span>¥{{ shippingFee }}</span>
                      </div>
                    </template>

                    <!-- 酒店订单费用明细 -->
                    <template v-if="orderType === 'hotel'">
                      <div
                        class="flex justify-between text-gray-500 dark:text-gray-400"
                      >
                        <div>
                          <span>房费</span>
                          <span class="text-sm ml-2">
                            ({{ formData.roomCount || 1 }}间 ×
                            {{ calculateNights() }}晚 × ¥{{
                              orderItems[0]?.price || 0
                            }})
                          </span>
                        </div>
                        <span>¥{{ calculateRoomFee() }}</span>
                      </div>
                      <div
                        class="flex justify-between text-gray-500 dark:text-gray-400"
                      >
                        <span>服务费</span>
                        <span>¥{{ calculateServiceFee() }}</span>
                      </div>
                    </template>

                    <!-- 特色体验订单费用明细 -->
                    <template v-if="orderType === 'experience'">
                      <div
                        class="flex justify-between text-gray-500 dark:text-gray-400"
                      >
                        <div>
                          <span>体验费用</span>
                          <span class="text-sm ml-2">
                            ({{ formData.participants?.length || 1 }}人 × ¥{{
                              orderItems[0]?.price || 0
                            }})
                          </span>
                        </div>
                        <span>¥{{ calculateExperienceFee() }}</span>
                      </div>
                      <div
                        class="flex justify-between text-gray-500 dark:text-gray-400"
                      >
                        <span>服务费</span>
                        <span>¥{{ calculateExperienceServiceFee() }}</span>
                      </div>
                    </template>

                    <div
                      class="flex justify-between text-lg font-medium pt-4 border-t border-gray-100 dark:border-gray-700"
                    >
                      <span class="dark:text-gray-100">总计</span>
                      <span
                        class="text-primary-600 dark:text-primary-400 text-xl"
                        >¥{{ calculateTotalAmount() }}</span
                      >
                    </div>
                  </div>

                  <!-- 订单备注 -->
                  <div class="mt-6 space-y-2">
                    <h3 class="text-base font-medium dark:text-gray-100">
                      订单备注
                    </h3>
                    <el-input
                      v-model="formData.remark"
                      type="textarea"
                      :rows="3"
                      :placeholder="getRemarkPlaceholder"
                      maxlength="200"
                      show-word-limit
                      class="dark:text-gray-300"
                    />
                  </div>

                  <!-- 提交按钮 -->
                  <el-button
                    type="primary"
                    class="w-full mt-6 !h-12 text-base dark:bg-primary-600 dark:border-primary-600 dark:hover:bg-primary-700 dark:hover:border-primary-700"
                    :loading="submitting"
                    @click="handleSubmit"
                  >
                    提交订单
                  </el-button>

                  <!-- 温馨提示 -->
                  <div
                    class="mt-4 text-xs text-gray-400 dark:text-gray-500 leading-relaxed"
                  >
                    <p>温馨提示：</p>
                    <p>1. 请仔细核对订单信息，提交后将无法修改</p>
                    <p>2. 如需帮助，请联系客服 400-xxx-xxxx</p>
                  </div>
                </div>
              </div>
            </div>
          </el-form>
        </template>
      </div>
    </div>

    <!-- 地址选择弹窗 -->
    <el-dialog
      v-model="showAddressDialog"
      title="选择收货地址"
      width="640px"
      destroy-on-close
    >
      <div class="address-list space-y-4 max-h-[60vh] overflow-y-auto px-1">
        <div
          v-for="address in addressList"
          :key="address.id"
          class="address-item group"
          :class="{ 'is-active': selectedAddress?.id === address.id }"
          @click="selectAddress(address)"
        >
          <div class="flex items-start">
            <div
              class="relative flex items-center justify-center w-5 h-5 mt-1.5 mr-4 rounded-full border transition-colors duration-200"
              :class="[
                selectedAddress?.id === address.id
                  ? 'border-primary-600 bg-primary-600'
                  : 'border-gray-300 bg-white',
              ]"
            >
              <div
                v-if="selectedAddress?.id === address.id"
                class="absolute w-2 h-2 rounded-full bg-white"
              />
            </div>
            <div class="address-content">
              <div class="flex items-center mb-2">
                <span class="font-medium text-lg">{{ address.name }}</span>
                <span class="text-gray-500 mx-4">{{ address.phone }}</span>
                <el-tag v-if="address.isDefault" size="small" type="primary">
                  默认地址
                </el-tag>
              </div>
              <div class="text-gray-600 text-sm leading-relaxed">
                {{ address.fullAddress }}
              </div>
            </div>
          </div>
          <div class="address-actions opacity-0 group-hover:opacity-100">
            <el-button
              type="primary"
              link
              @click.stop="handleEditAddress(address)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              @click.stop="handleDeleteAddress(address)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="flex justify-between items-center">
          <el-button @click="handleAddAddress">
            <el-icon class="mr-1"><Plus /></el-icon>
            新增地址
          </el-button>
          <div class="space-x-2">
            <el-button @click="showAddressDialog = false">取消</el-button>
            <el-button
              type="primary"
              :disabled="!selectedAddress"
              @click="handleConfirmAddress"
            >
              确定
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  ArrowLeft,
  WechatFilled,
  Alipay,
  Plus,
  Location,
  ArrowRight,
  ShoppingBag,
  CircleClose,
  Ticket,
  Clock,
  Timer,
  InfoFilled,
  QuestionFilled,
  Sunny,
  Picture,
} from "@element-plus/icons-vue";
import dayjs from "dayjs";
import axios from "@/api/axios"; // 导入axios实例

const router = useRouter();
const route = useRoute();

// 页面状态
const loading = ref(true);
const currentStep = ref(0);
const formRef = ref(null);
const submitting = ref(false);

// 订单类型
const orderType = ref("");

// 表单数据
const formData = ref({
  // 通用字段
  remark: "",

  // 商品订单字段
  addressId: "",

  // 酒店订单字段
  checkIn: "",
  checkOut: "",
  guests: [{ name: "", idType: "idcard", idNumber: "" }],

  // 门票订单字段
  visitDate: "",
  visitors: [{ name: "", phone: "", idNumber: "" }],

  // 特色体验订单字段
  experienceDate: "",
  participants: [{ name: "", phone: "", idNumber: "" }],

  // 导游订单字段
  contactPerson: {
    name: "",
    phone: "",
    idNumber: "",
  },
  people: 1,
});

// 表单验证规则
const formRules = {
  addressId: [{ required: true, message: "请选择收货地址" }],
  checkIn: [{ required: true, message: "请选择入住日期" }],
  checkOut: [{ required: true, message: "请选择离店日期" }],
  visitDate: [{ required: true, message: "请选择游玩日期" }],
};

// 收货地址相关
const showAddressDialog = ref(false);
const selectedAddress = ref(null);
const addressList = ref([
  {
    id: 1,
    name: "张三",
    phone: "13800138000",
    province: "广西壮族自治区",
    city: "贵港市",
    district: "港北区",
    address: "贵港大道123号",
    isDefault: true,
    fullAddress: "广西壮族自治区贵港市港北区贵港大道123号",
  },
]);

// 商品信息
const orderItems = ref([
  {
    id: 1,
    title: "贵港特色手工艺品",
    specs: "规格：标准款",
    price: 99,
    originalPrice: 129,
    quantity: 1,
    stock: 10,
    image: "/images/products/product1.jpg",
  },
]);

// 最大入住人/游客数量
const maxGuests = 4;
const maxVisitors = ref(10);

// 最大参与人数
const maxParticipants = ref(10);

// 运费
const shippingFee = ref(0);

// 天气信息
const weatherInfo = ref({
  temperature: "26°C-32°C",
  condition: "晴",
  suitable: true,
  tips: "天气晴朗，适合游玩，请做好防晒",
});

// 景点信息
const spotInfo = ref({
  openTime: "09:00-17:30",
  suggestedTime: "2-3小时",
  address: "广西贵港市港北区江滨路1号",
  tips: "请携带有效证件，景区提供免费讲解服务",
});

// 计算属性
const getOrderItemTitle = computed(() => {
  switch (orderType.value) {
    case "product":
      return "商品信息";
    case "hotel":
      return "房间信息";
    case "experience":
      return "体验信息";
    case "ticket":
      return "门票信息";
    case "guide":
      return "导游信息";
    default:
      return "订单信息";
  }
});

const getOrderAmountLabel = computed(() => {
  switch (orderType.value) {
    case "hotel":
      return "房费总额";
    case "ticket":
      return "门票总额";
    case "experience":
      return "体验费用总额";
    default:
      return "商品总额";
  }
});

const getRemarkPlaceholder = computed(() => {
  switch (orderType.value) {
    case "hotel":
      return "请输入特殊要求（如无烟房、高层房等），酒店会尽量安排";
    case "ticket":
      return "请输入特殊需求（如轮椅租赁、导游需求等）";
    case "experience":
      return "请输入特殊需求（如轮椅租赁、导游需求等）";
    default:
      return "请输入订单备注（选填）";
  }
});

// 计算商品总额
const calculateProductTotal = () => {
  return orderItems.value.reduce((total, item) => {
    return total + item.price * item.quantity;
  }, 0);
};

// 计算房费
const calculateRoomFee = () => {
  if (!orderItems.value.length) return 0;
  const price = orderItems.value[0].price || 0;
  const nights = calculateNights();
  const roomCount = formData.value.roomCount || 1;
  return price * nights * roomCount;
};

// 计算服务费（10%）
const calculateServiceFee = () => {
  return Math.floor(calculateRoomFee() * 0.1);
};

// 计算特色体验费用
const calculateExperienceFee = () => {
  if (!orderItems.value.length) return 0;
  const price = orderItems.value[0].price || 0;
  const participantCount = formData.value.participants?.length || 1;
  return price * participantCount;
};

// 计算特色体验服务费（5%）
const calculateExperienceServiceFee = () => {
  return Math.floor(calculateExperienceFee() * 0.05);
};

// 计算总金额
const calculateTotalAmount = () => {
  if (orderType.value === "product") {
    return calculateProductTotal() + shippingFee.value;
  } else if (orderType.value === "hotel") {
    return calculateRoomFee() + calculateServiceFee();
  } else if (orderType.value === "experience") {
    return calculateExperienceFee() + calculateExperienceServiceFee();
  } else if (orderType.value === "guide") {
    // 导游服务费用计算逻辑
    return orderItems.value[0]?.price || 0;
  }
  return 0;
};

// 日期相关方法
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7;
};

const disabledCheckoutDate = (time) => {
  if (!formData.value.checkIn) return false;
  return time.getTime() <= dayjs(formData.value.checkIn).valueOf();
};

// 获取最大可购买数量
const getMaxQuantity = (item) => {
  switch (orderType.value) {
    case "hotel":
      return item.stock;
    case "ticket":
      return Math.min(
        item.stock,
        maxVisitors.value - formData.value.visitors.length,
      );
    case "experience":
      return Math.min(
        item.stock,
        maxVisitors.value - formData.value.participants.length,
      );
    default:
      return item.stock;
  }
};

// 计算入住天数
const calculateNights = () => {
  if (!formData.value.checkIn || !formData.value.checkOut) return 0;
  return dayjs(formData.value.checkOut).diff(
    dayjs(formData.value.checkIn),
    "day",
  );
};

// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format("YYYY-MM-DD") : "";
};

// 验证证件号码
const validateIdNumber = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入证件号码"));
    return;
  }

  const idType = formData.value.guests?.[0]?.idType;
  if (idType === "idcard") {
    const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (!reg.test(value)) {
      callback(new Error("请输入正确的身份证号码"));
      return;
    }
  }
  callback();
};

// 事件处理方法
const handleBack = () => {
  router.back();
};

const handleQuantityChange = () => {
  // 重新计算订单金额
};

const handleCouponChange = () => {
  // 重新计算优惠金额
};

// 获取用户地址列表
const fetchAddressList = async () => {
  try {
    const response = await axios.get("/user/addresses");
    if (response && response.length) {
      addressList.value = response;
      
      // 如果有默认地址，自动选中
      const defaultAddress = addressList.value.find(addr => addr.isDefault);
      if (defaultAddress) {
        selectedAddress.value = defaultAddress;
        formData.value.addressId = defaultAddress.id;
      }
    }
  } catch (error) {
    console.error("获取地址列表失败:", error);
    // 使用测试数据
  }
};

const selectAddress = (address) => {
  selectedAddress.value = address;
  formData.value.addressId = address.id;
};

const handleConfirmAddress = () => {
  if (!selectedAddress.value) {
    ElMessage.warning("请选择收货地址");
    return;
  }
  showAddressDialog.value = false;
};

const handleEditAddress = async (address) => {
  // TODO: 实现编辑地址功能
};

const handleDeleteAddress = async (address) => {
  try {
    await ElMessageBox.confirm("确定要删除该收货地址吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    
    try {
      await axios.delete(`/user/addresses/${address.id}`);
      ElMessage.success("删除成功");
      await fetchAddressList(); // 重新加载地址列表
    } catch (error) {
      console.error("删除地址失败:", error);
      ElMessage.error("删除地址失败");
    }
  } catch {
    // 用户取消删除
  }
};

const handleAddAddress = () => {
  // TODO: 实现新增地址功能
  router.push("/user/address/add");
};

// 添加/删除入住人
const addGuest = () => {
  if (formData.value.guests.length < maxGuests) {
    formData.value.guests.push({ name: "", idType: "idcard", idNumber: "" });
  }
};

const removeGuest = (index) => {
  formData.value.guests.splice(index, 1);
};

// 添加/删除体验者
const addParticipant = () => {
  if (formData.value.participants.length < maxParticipants.value) {
    formData.value.participants.push({
      name: "",
      phone: "",
      idNumber: "",
    });
  }
};

const removeParticipant = (index) => {
  formData.value.participants.splice(index, 1);
};

// 添加/删除游客
const addVisitor = () => {
  if (formData.value.visitors.length < maxVisitors.value) {
    formData.value.visitors.push({
      name: "",
      phone: "",
      idNumber: "",
    });
  }
};

const removeVisitor = (index) => {
  formData.value.visitors.splice(index, 1);
};

// 提交订单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    loading.value = true;
    submitting.value = true;

    // 创建订单数据
    const orderData = {
      type: orderType.value,
      items: orderItems.value.map((item) => ({
        id: item.id,
        title: item.title,
        image: item.image,
        price: item.price,
        quantity: item.quantity || 1,
      })),
      remark: formData.value.remark,
      // 不同类型订单的特定数据
      booking:
        orderType.value === "hotel"
          ? {
              checkIn: dayjs(formData.value.checkIn).format("YYYY-MM-DD"),
              checkOut: dayjs(formData.value.checkOut).format("YYYY-MM-DD"),
              roomCount: formData.value.roomCount || 1,
              guestCount: formData.value.guests.length,
              guests: formData.value.guests,
              totalAmount: calculateRoomFee(),
              serviceFee: calculateServiceFee(),
            }
          : orderType.value === "ticket"
            ? {
                visitDate: dayjs(formData.value.visitDate).format("YYYY-MM-DD"),
                visitors: formData.value.visitors,
                spotAddress: formData.value.spotAddress || spotInfo.value.address,
              }
            : orderType.value === "experience"
              ? {
                  experienceDate: dayjs(formData.value.experienceDate).format(
                    "YYYY-MM-DD",
                  ),
                  participantCount: formData.value.participants?.length || 1,
                  participants: formData.value.participants,
                  totalAmount: calculateExperienceFee(),
                  serviceFee: calculateExperienceServiceFee(),
                }
              : orderType.value === "guide"
                ? {
                    guideDate: dayjs(formData.value.guideDate).format(
                      "YYYY-MM-DD",
                    ),
                    guideTime: formData.value.guideTime,
                    contactPerson: formData.value.contactPerson,
                    people: formData.value.people,
                    routeId: formData.value.routeId,
                    routeName: formData.value.routeName,
                  }
                : null,
      // 商品订单特定数据
      address:
        orderType.value === "product"
          ? selectedAddress.value
          : null,
      shippingFee: orderType.value === "product" ? shippingFee.value : 0,
    };

    try {
      // 调用创建订单API
      const response = await axios.post("/orders", orderData);
      
      // 成功创建订单后跳转到支付页面
      const orderNo = response.orderNo || response.id || `ORD${Date.now()}`;
      
      const encodedData = encodeURIComponent(JSON.stringify({
        orderNo: orderNo,
        title: orderItems.value[0]?.title || "订单",
        type: orderType.value,
        createTime: new Date(),
        payableAmount: calculateTotalAmount(),
        booking: orderData.booking,
      }));
      
      router.push({
        path: "/order/payment",
        query: {
          orderId: orderNo,
          data: encodedData,
        },
      });
      
    } catch (error) {
      console.error("创建订单失败:", error);
      ElMessage.error("订单提交失败");

      // 模拟创建订单，使用测试数据
      const orderNo = `ORD${Date.now()}`;
      
      const encodedData = encodeURIComponent(JSON.stringify({
        orderNo: orderNo,
        title: orderItems.value[0]?.title || "订单",
        type: orderType.value,
        createTime: new Date(),
        payableAmount: calculateTotalAmount(),
        booking: orderData.booking,
      }));
      
      router.push({
        path: "/order/payment",
        query: {
          orderId: orderNo,
          data: encodedData,
        },
      });
    }
  } catch (error) {
    loading.value = false;
    submitting.value = false;
    console.error("订单提交失败:", error);
    ElMessage.error("订单提交失败，请检查表单信息");
  } finally {
    loading.value = false;
    submitting.value = false;
  }
};

// 获取天气信息
const fetchWeatherInfo = async () => {
  try {
    // 尝试从API获取天气信息
    const response = await axios.get("/public/weather", {
      params: { city: "贵港" }
    });
    
    if (response) {
      weatherInfo.value = response;
    }
  } catch (error) {
    console.error("获取天气信息失败:", error);
    // 使用测试数据
  }
};

// 加载可用优惠券
const loadAvailableCoupons = async () => {
  try {
    // 尝试从API获取优惠券
    const response = await axios.get("/user/coupons/available", {
      params: { 
        type: orderType.value,
        amount: calculateTotalAmount()
      }
    });
    
    if (response && response.length) {
      // 处理优惠券数据
    }
  } catch (error) {
    console.error("获取优惠券列表失败:", error);
    // 使用测试数据
  }
};

// 倒计时相关
let countdownTimer = null;
const countdown = ref(900); // 15分钟倒计时

// 开始倒计时
const startCountdown = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  countdownTimer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(countdownTimer);
      ElMessage.warning("订单已超时，请重新预订");
      router.push("/hotel");
    }
  }, 1000);
};

// 页面加载
onMounted(async () => {
  try {
    const { type, data } = route.query;

    if (!type) {
      throw new Error("订单类型错误");
    }

    // 设置订单类型
    orderType.value = type;
    
    // 获取地址列表(如果是商品订单)
    if (type === "product") {
      await fetchAddressList();
    }

    // 处理门票订单
    if (type === "ticket" && data) {
      const ticketData = JSON.parse(decodeURIComponent(data));
      console.log("门票数据:", ticketData);

      // 设置订单项
      orderItems.value = [
        {
          id: ticketData.ticketId,
          title: `${ticketData.spotName} - ${ticketData.ticketName}`,
          image: ticketData.spotImage,
          price: ticketData.price,
          specs: ticketData.description,
          quantity: 1,
        },
      ];

      // 初始化表单数据
      formData.value = {
        visitDate: null,
        visitors: [
          {
            name: "",
            phone: "",
            idNumber: "",
          },
        ],
        remark: "",
        spotAddress: ticketData.address || spotInfo.value.address,
      };

      // 获取天气信息
      await fetchWeatherInfo();
    }
    // 处理商品订单
    else if (type === "product" && data) {
      // ... existing product order logic ...
    }
    // 处理酒店订单
    else if (type === "hotel" && data) {
      // ... existing hotel order logic ...
    }
    // 处理特色体验订单
    else if (type === "experience" && data) {
      const experienceData = JSON.parse(decodeURIComponent(data));
      console.log("体验数据:", experienceData);

      // 设置订单项
      orderItems.value = [
        {
          id: experienceData.experienceId,
          title: experienceData.experienceName,
          image: experienceData.experienceImage,
          price: experienceData.price,
          specs: experienceData.description,
          quantity: 1,
        },
      ];

      // 初始化表单数据
      formData.value = {
        experienceDate: dayjs(experienceData.date).toDate(),
        participants: [
          {
            name: "",
            phone: "",
            idNumber: "",
          },
        ],
        remark: "",
      };
    }
    // 处理导游预约订单
    else if (type === "guide" && data) {
      const guideData = JSON.parse(decodeURIComponent(data));
      console.log("导游数据:", guideData);

      // 设置订单类型
      orderType.value = "guide";

      // 设置订单项
      orderItems.value = [
        {
          id: guideData.guideId,
          title: `${guideData.guideName} - ${guideData.routeName || "导游服务"}`,
          image: guideData.guideAvatar,
          price: guideData.price,
          specs: `预约日期: ${guideData.date}, 开始时间: ${guideData.startTime}`,
          quantity: 1,
        },
      ];

      // 初始化表单数据
      formData.value = {
        guideDate: dayjs(guideData.date).toDate(),
        guideTime: guideData.startTime,
        people: guideData.people || 1,
        phone: guideData.phone || "",
        contactPerson: {
          name: "",
          phone: guideData.phone || "",
          idNumber: "",
        },
        routeId: guideData.routeId,
        routeName: guideData.routeName,
        remark: guideData.remarks || "",
      };
    } else {
      throw new Error("无效的订单数据");
    }

    // 加载可用优惠券
    await loadAvailableCoupons();

    // 开始倒计时
    startCountdown();
  } catch (error) {
    console.error("初始化订单失败:", error);
    ElMessage.error(error.message || "初始化订单失败");
    router.back();
  } finally {
    loading.value = false;
  }
});

// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
</script>

<style lang="scss" scoped>
.order-confirm-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  // 主要内容区
  .order-content {
    @apply space-y-6;

    // 通用卡片样式
    .section-card {
      @apply bg-white rounded-lg shadow-sm dark:bg-gray-800 dark:border dark:border-gray-700;

      .section-title {
        @apply text-lg font-medium text-gray-900 dark:text-gray-100 mb-4;
      }
    }

    // 地址选择
    .address-item {
      @apply flex items-start justify-between p-5 border border-gray-200 dark:border-gray-700 rounded-lg mb-4 cursor-pointer transition-all duration-200;

      &:hover {
        @apply border-primary-500 bg-primary-50/50 dark:bg-primary-900/20 shadow-sm;
        transform: translateY(-1px);
      }

      &.is-active {
        @apply border-primary-500 bg-primary-50/50 dark:bg-primary-900/20 shadow-sm;
      }

      .address-content {
        @apply flex-1;

        .contact {
          @apply text-gray-900 dark:text-gray-100 font-medium mb-2;

          .phone {
            @apply ml-4 text-gray-500 dark:text-gray-400;
          }
        }

        .address {
          @apply text-gray-600 dark:text-gray-300 text-sm leading-relaxed;
        }
      }

      .address-actions {
        @apply ml-4 space-x-2 opacity-0 transition-all duration-200;
      }

      &:hover .address-actions {
        @apply opacity-100;
      }
    }

    // 入住人和游客表单
    .guest-info,
    .visitor-info {
      .guest-item,
      .visitor-item {
        @apply bg-gray-50/70 dark:bg-gray-800/70 rounded-lg p-5 transition-all duration-200;

        &:hover {
          @apply bg-gray-100/70 dark:bg-gray-700/70 shadow-sm;
          transform: translateY(-1px);
        }
      }
    }

    // 商品列表
    .product-list {
      @apply divide-y divide-gray-100 dark:divide-gray-700;

      .product-item {
        @apply flex items-center p-6 transition-all duration-200;

        &:hover {
          @apply bg-gray-50 dark:bg-gray-800;
        }

        .product-image {
          @apply w-24 h-24 rounded-lg object-cover flex-shrink-0 bg-gray-100;
        }

        .product-info {
          @apply flex-1 min-w-0 ml-6;

          .product-title {
            @apply text-base font-medium text-gray-900 dark:text-gray-100 mb-2 line-clamp-2 hover:text-primary-600 dark:hover:text-primary-400 transition-colors duration-200;
          }

          .product-specs {
            @apply text-sm text-gray-500 dark:text-gray-400;
          }
        }

        .product-price {
          @apply text-right ml-6;

          .current-price {
            @apply text-lg text-primary-600;
          }

          .original-price {
            @apply text-sm text-gray-400 line-through;
          }
        }
      }
    }
  }

  // 订单金额
  .order-summary {
    @apply bg-white dark:bg-gray-800 rounded-lg p-6 lg:sticky lg:top-24 transition-shadow duration-200 dark:border dark:border-gray-700;

    &:hover {
      @apply shadow-md;
    }

    .summary-item {
      @apply flex items-center justify-between py-2;

      .label {
        @apply text-gray-500 dark:text-gray-400;
      }

      .value {
        @apply text-gray-900 dark:text-gray-100 font-medium;

        &.discount {
          @apply text-primary-600 dark:text-primary-400;
        }
      }
    }

    .submit-btn {
      @apply w-full mt-6 !h-12 text-base font-medium transition-all duration-200;

      &:not(:disabled):hover {
        transform: translateY(-1px);
        @apply shadow-md;
      }
    }
  }
}

// 弹窗样式
:deep {
  .el-dialog {
    @apply dark:bg-gray-800;

    .el-dialog__header {
      @apply border-b border-gray-100 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-700/50;
    }

    .el-dialog__body {
      @apply dark:text-gray-300;
    }

    .el-dialog__footer {
      @apply border-t border-gray-100 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-700/50;
    }
  }
}

// 表单样式
:deep {
  .el-form-item {
    &.is-error {
      .el-input__wrapper {
        @apply border-red-500 dark:border-red-400;
      }

      .el-form-item__error {
        @apply text-red-500 dark:text-red-400;
      }
    }
  }
}

// 输入框样式
:deep {
  .el-input {
    .el-input__wrapper {
      @apply border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100;

      &:hover {
        @apply border-gray-400 dark:border-gray-500;
      }

      &.is-focus {
        @apply border-primary-500 dark:border-primary-400;
      }
    }
  }
}

// 选择器样式
:deep {
  .el-select {
    .el-input {
      @apply w-full;
    }

    .el-select__tags {
      @apply mx-2;
    }
  }
}

// 日期选择器样式
:deep {
  .el-date-picker {
    @apply rounded-lg border-none;
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  }
}

// 数字输入框样式
:deep {
  .el-input-number {
    @apply w-32;

    .el-input-number__decrease,
    .el-input-number__increase {
      @apply border-gray-300 transition-colors duration-200;

      &:hover {
        @apply bg-gray-50 text-primary-600;
      }
    }
  }
}

// 单选框样式
:deep {
  .el-radio {
    @apply mb-0;

    &.is-checked {
      .el-radio__inner {
        @apply border-primary-600 bg-primary-600;
      }

      .el-radio__label {
        @apply text-primary-600;
      }
    }

    &.is-bordered {
      @apply border-gray-200 rounded-lg transition-all duration-200;

      &:hover {
        @apply border-primary-500 shadow-sm;
        transform: translateY(-1px);
      }

      &.is-checked {
        @apply border-primary-500 bg-primary-50;
      }
    }
  }
}

// 标签样式
:deep {
  .el-tag {
    @apply rounded-md;

    &.el-tag--primary {
      @apply bg-primary-50 text-primary-600 border-primary-200;
    }
  }
}

// 地址选择弹窗样式
.address-list {
  .address-item {
    @apply flex items-start justify-between p-5 border border-gray-200 rounded-lg cursor-pointer transition-all duration-200;

    &:hover {
      @apply border-primary-500 bg-primary-50/50;
    }

    &.is-active {
      @apply border-primary-500 bg-primary-50/50;
    }

    .address-content {
      @apply flex-1;
    }

    .address-actions {
      @apply ml-4 space-x-2 opacity-0 transition-all duration-200;
    }

    &:hover .address-actions {
      @apply opacity-100;
    }
  }
}

// 优惠券卡片样式
.coupon-card {
  @apply relative flex items-stretch rounded-lg overflow-hidden transition-all duration-200;
  min-height: 88px;

  &.empty {
    @apply border border-dashed border-gray-300 dark:border-gray-600;

    &:hover {
      @apply border-primary-500 dark:border-primary-400 bg-primary-50/30 dark:bg-primary-900/30;
    }
  }

  &.selected {
    @apply border border-primary-500 dark:border-primary-400 bg-primary-50/50 dark:bg-primary-900/20;
  }

  &.is-active {
    @apply border border-primary-500 dark:border-primary-400 bg-primary-50/50 dark:bg-primary-900/20;
  }

  &.is-disabled {
    @apply opacity-60 cursor-not-allowed;
  }

  .coupon-left {
    @apply flex flex-col items-center justify-center px-6 py-4 bg-primary-600 text-white;
    min-width: 120px;

    .amount {
      @apply flex items-baseline;

      .symbol {
        @apply text-lg;
      }

      .value {
        @apply text-3xl font-medium ml-0.5;
      }
    }

    .condition {
      @apply text-xs mt-1 text-primary-100;
    }
  }

  .coupon-right {
    @apply flex-1 flex flex-col justify-center p-4 bg-white dark:bg-gray-800;

    .name {
      @apply text-base font-medium text-gray-900 dark:text-gray-100;
    }

    .date {
      @apply text-xs text-gray-500 dark:text-gray-400;
    }
  }
}

// 支付方式卡片样式
.payment-method-card {
  @apply flex flex-col items-center justify-center p-6 border-2 border-gray-200 dark:border-gray-700 dark:bg-gray-800;

  img {
    @apply w-12 h-12 mb-3 transition-transform duration-200;
  }

  span {
    @apply text-gray-600 dark:text-gray-300;
  }

  &:hover {
    @apply border-primary-500 dark:border-primary-400 bg-primary-50 dark:bg-primary-900/20;

    img {
      transform: scale(1.05);
    }

    span {
      @apply text-primary-600 dark:text-primary-400;
    }
  }

  &.is-active {
    @apply border-primary-500 dark:border-primary-400 bg-primary-50 dark:bg-primary-900/20;
    box-shadow: 0 0 0 1px theme("colors.primary.500");

    span {
      @apply text-primary-600 dark:text-primary-400;
    }
  }
}
</style>
